package com.mall.czlr.base.advice;

import com.mall.czlr.base.common.ErrorResponse;
import com.mall.czlr.base.exception.BaseException;
import com.mall.czlr.base.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Exception.class, RuntimeException.class, Throwable.class})
    public ErrorResponse exceptionHandler(HttpServletRequest request, Exception e) {
        ErrorResponse errorResponse = new ErrorResponse(BaseException.ERROR_IN_INTERCEPTOR, "an error occurred");

        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            errorResponse.setCode(ex.getCode());
            errorResponse.setMessage(ex.getMessage());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();

            errorResponse.setCode(BaseException.ERROR_WRONG_PARAM);
            errorResponse.setMessage(msg);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            errorResponse.setCode(BaseException.ERROR_REQUEST_METHOD_NOT_SUPPORTED);
            errorResponse.setMessage("请求方法不支持");
        } else {
            errorResponse.setCode(BaseException.ERROR_IN_INTERCEPTOR);
            errorResponse.setMessage("拦截错误");
        }

        return errorResponse;
    }
}
